import { User } from '@libs /db/Entitys/User.Enitty';
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class JwtGuard implements CanActivate {
  constructor(
    private readonly JwtService: JwtService,
    @InjectRepository(User) private readonly UserEntity: Repository<User>,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const res = context.switchToHttp().getResponse();
    try {
      const accessToken = req.get('Authorization');
      if (!accessToken) throw new UnauthorizedException('请先登录');
      const atUserId = this.JwtService.verify(
        accessToken.replace('Bearer ', ''),
      );
      if (!atUserId) throw new UnauthorizedException('认证失败');
      const data = await this.UserEntity.findOne({
        where: {
          id: atUserId,
        },
      });
      if (data) {
        req.user = data;
        return true;
      } else {
        throw new UnauthorizedException('用户不存在');
      }
    } catch (error) {
      throw new UnauthorizedException('Token不存在');
    }
  }
}
